﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
using System.Collections.Specialized;
using System.Diagnostics;

namespace BizTalkOneService
{
    class FileCount
    {
        EventLog appLog = new EventLog();
        private List<FilePath> FilePathList = new List<FilePath>();
        public FileCount()
        {
            var filePaths = ConfigurationManager.GetSection("files") as NameValueCollection;
            if (filePaths != null)
            {
                foreach (var nameKey in filePaths.AllKeys)
                {
                    FilePathList.Add(new FilePath { FilePathKey = nameKey.ToString(), FilePathValue = filePaths.GetValues(nameKey).FirstOrDefault() });
                }
            }
        }

        public List<Counter> GetFilePaths()
        {
            List<Counter> CounterList = new List<Counter>();
            foreach (FilePath fp in FilePathList)
                try
                {
                    int count = Convert.ToInt32(Directory.GetFiles(fp.FilePathValue, "*.*", SearchOption.TopDirectoryOnly).Length);
                    CounterList.Add(new Counter { CounterCategory = "File", CounterName = fp.FilePathKey, CounterValue = count }); 
                }
                catch (Exception ex)
                {
                    appLog.Source = Settings.EventLogSource;
                    EventLogEntryType eventType = EventLogEntryType.Error;
                    appLog.WriteEntry(ex.Message, eventType);
                    CounterList.Add(new Counter() { CounterCategory = "Error", CounterName = "File", CounterValueString = String.Format("{0}: {1}", fp.FilePathValue, ex.Message.ToString()) });
                }
            return CounterList;
        }

    }
}
